<template>
  <table id="TableToExport">
    <thead>
    <tr>
      <th>版本</th>
      <th>姓名</th>
      <th>项目</th>
      <th>成绩</th>
      <th>操作</th>
    </tr>
    </thead>
    <tbody>
    <tr v-for="n in initData" :key="n.id">
      <td>{{ n.id }}</td>
      <td>{{ n.name }}</td>
      <td>{{ n.project }}</td>
      <td>{{ n.results }}</td>
      <td @click="deleteC(n.id)" style="cursor:pointer">删除</td>
    </tr>
    </tbody>
  </table>

  <!-- 上传 -->
  <input type="file" @change="inputFile($event)" accept=".xlsx, .xls, .csv"/>

  <!--  <el-upload-->
  <!--      class="upload-demo inline-block"-->
  <!--      action="/"-->
  <!--      :on-change="getExcel"-->
  <!--      :auto-upload="false"-->
  <!--      :show-file-list="false"-->
  <!--      style="width: 140px"-->
  <!--  >-->
  <!--    <el-button class="margin-change" plain>导入</el-button>-->
  <!--  </el-upload>-->
  <button @click="exportExcel">导出</button>

</template>

<script setup lang="ts">
import {defineComponent, reactive, ref} from 'vue';
import * as XLSX from 'xlsx'
// import {ElMessage, ElMessageBox} from 'element-plus'
import {workbook2blob, openDownloadDialog, file2Xce} from "@/utils/exceldown.js";
import {InitDataEnum} from "@/enums/initData";
import {v4 as uuid} from "uuid";

let initData = reactive([
  {
    id: '1',
    name: '王大',
    project: 'spring',
    results: '优秀',
  },
  {
    id: '2',
    name: '王二',
    project: 'vue',
    results: '及格',
  }, {
    id: '3',
    name: '王三',
    project: 'react',
    results: '良好',
  }
]);

let deleteC = (id) => {
  let index = initData.findIndex(x => x.id === id);
  initData.splice(index, 1);
}

/**
 * 导出excel
 */
let exportExcel = () => {
  const tableDom = document.querySelector('#TableToExport')
  const workbook = XLSX.utils.table_to_book(tableDom)
  //  文件名带后缀
  XLSX.writeFileXLSX(workbook, '表1.xlsx')
}

const getExcel = (file) => {
  // 获取文件后缀类型
  const types = file.name.split(".")[1];
  const fileType = ["xlsx", "xlc", "xlm", "xls", "xlt", "xlw", "csv"].some(
      (item) => item === types
  );
  if (!fileType) {
    // ElMessage.error('格式错误！请重新选择')
    console.log("格式错误！请重新选择");
    return;
  }
  file2Xce(file).then((tabJson) => {
    if (tabJson && tabJson.length > 0) {
      //成功解析出数据
      let dataSheet = tabJson[0].sheet;
      // 解析完成之后展示信息
      dataSheet.forEach(function (value, index, array) {
        initData.push({
          // 使用导入的id
          // id: value[InitDataEnum.id],
          // id递增
          // id: initData.length+1,
          // id随机
          id: uuid(),
          name: value[InitDataEnum.name],
          project: value[InitDataEnum.project],
          results: value[InitDataEnum.results]
        })
      })
      // ElMessage.success('导入数据成功')
      console.log("导入数据成功");
    }
  });
}

/**
 * 导出表格
 */
let inputFile = (e) => {
  const file = e.target.files[0]
  const fileReader = new FileReader();
  fileReader.onload = ev => {
    try {
      const data = ev.target.result;
      const workbook = XLSX.read(data, {type: "binary"});
      const params = [];
      // 取对应表生成json表格内容
      workbook.SheetNames.forEach(item => {
        params.push({
          name: item,
          dataList: XLSX.utils.sheet_to_json(workbook.Sheets[item])
        });
        XLSX.utils.sheet_to_json(workbook.Sheets[item]).forEach(function (currentValue, index, array) {
          // 在这里执行对当前元素的操作
          // console.log("current:",currentValue);
          // console.log("name:",currentValue[InitDataEnum.name]);
          // console.log("project:",currentValue[InitDataEnum.project]);
          // console.log("results:",currentValue[InitDataEnum.results]);
          initData.push({
            // 使用导入的id
            // id: value[InitDataEnum.id],
            // id递增
            id: (initData.length + 1).toString(),
            // id随机
            // id: uuid(),
            name: currentValue[InitDataEnum.name].toString(),
            project: currentValue[InitDataEnum.project].toString(),
            results: currentValue[InitDataEnum.results].toString()
          })
        })
      });
      // 重写数据
    } catch (e) {
      console.log("error:" + e);
      return false;
    }
  };
  fileReader.readAsBinaryString(file);
}

</script>

<style scoped>
.inline-block {
  display: inline-block;
  margin-right: 10px;
}

.margin-change {
  display: inline-block;
  margin-left: 10px;
}
</style>